package com.haier.npt.sso.authentication;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
import org.springframework.util.Assert;

import com.haier.npt.sso.authentication.cache.TokenCacheService;
import com.haier.npt.sso.i18n.SSOMessageCode;
import com.haier.npt.sso.oauth.OauthService;
import com.haier.npt.utils.MessageHelper;


/**
 * 认证提供者
 * @author lixu
 *
 */

public class CustomPreAuthenticatedAuthenticationProvider extends PreAuthenticatedAuthenticationProvider {
	
	private OauthService oauthService ; 

	@Autowired
	private TokenCacheService tokenCacheService;

	@Autowired
	MessageHelper messageHelper;

	
	public void setOauthService(OauthService oauthService) {
		this.oauthService = oauthService;
	}


	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String token = (String)authentication.getPrincipal(); 
		
		if(tokenCacheService.hasKey(token)){
			//这里验证token 有效性
			boolean flag = oauthService.validate(token);  
			if(!flag){
				throw new TokenAuthenticationException(
						messageHelper.getMessage(SSOMessageCode.TOKEN_INVALID));
			}
		}else{
			throw new TokenAuthenticationException(
					messageHelper.getMessage(SSOMessageCode.TOKEN_INVALID));
		}

		
			
		return super.authenticate(authentication);
	}
	
	
	@Override
	public void afterPropertiesSet() {
		super.afterPropertiesSet();  
		Assert.notNull(oauthService, "An oauthService must be set");
	}
	
	
}
